package org.example.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sf.jsqlparser.util.SelectUtils;
import org.apache.commons.lang.time.DateUtils;
import org.example.config.AlipayConts;
import org.example.entity.PayLog;
import org.example.entity.PayPlan;
import org.example.entity.SysGoods;
import org.example.entity.SysMakeCode;
import org.example.service.IPayLogService;
import org.example.service.IPayPlanService;
import org.example.service.ISysGoodsService;
import org.example.service.ISysMakeCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhaowenting
 * @since 2024-04-02
 */
@RestController
@RequestMapping("/pay-plan")
public class PayPlanController {
    @Autowired
    ISysMakeCodeService iSysMakeCodeService;
    @Autowired
    ISysGoodsService iSysGoodsService;
    @Autowired
    IPayPlanService iPayPlanService;
    @Autowired
    IPayLogService iPayLogService;
    @RequestMapping("toPay")
    public String toPay(String outTradeNo) throws AlipayApiException {
        LambdaQueryWrapper<PayPlan> payPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        payPlanLambdaQueryWrapper.eq(PayPlan::getOutTradeNo,outTradeNo);
        PayPlan payPlan = iPayPlanService.getOne(payPlanLambdaQueryWrapper);
        AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地  址，仅支持http/https，公网可访问
        request.setNotifyUrl(AlipayConts.NOTIFY_URL);
//同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipayConts.RETURN_URL);
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", payPlan.getOutTradeNo());
//支付金额，最小值0.01元
        bizContent.put("total_amount", payPlan.getPrice());
//订单标题，不可使用特殊符号
        bizContent.put("subject", payPlan.getName());
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        Date date = DateUtils.addMinutes(payPlan.getCreateTime(), 2);
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
/******可选参数******/
        bizContent.put("time_expire", format);
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"POST");
// 如果需要返回GET请求，请使用
// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功 body="+response.getBody());
            return response.getBody();
        } else {
            System.out.println("=====调用支付失败==");
            return "error";
        }
    }
    //异步回掉
    @RequestMapping("alipayCallback")
    public void alipayCallback(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> paramMap = ServletUtil.getParamMap(request);
        boolean b = AlipaySignature.rsaCheckV1(paramMap, AlipayConts.ALIPAY_PUBLIC_KEY, AlipayConts.CHARSET, AlipayConts.SIGN_TYPE);
        System.out.println("验签结果：=="+b);
        String tradeStatus = paramMap.get("trade_status");
        if(b&& StrUtil.equalsIgnoreCase(AlipayConts.TRADE_SUCCESS,tradeStatus)){
            String outTradeNo = paramMap.get("out_trade_no");//订单号
            String tradeNo = paramMap.get("trade_no");//流水号
            iPayPlanService.doOrder(outTradeNo,tradeNo);

        }else{
            //状态state为5的时候为支付失败
            LambdaQueryWrapper<PayPlan> payPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
            payPlanLambdaQueryWrapper.eq(PayPlan::getOutTradeNo,paramMap.get("out_trade_no"));
            PayPlan payPlan = iPayPlanService.getOne(payPlanLambdaQueryWrapper);
            payPlan.setState(5);
            iPayPlanService.updateById(payPlan);
        }
    }
    //退款方法
    @RequestMapping("refund")
    public String refund(String outTradeNo) throws AlipayApiException {
        LambdaQueryWrapper<PayPlan> payPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        payPlanLambdaQueryWrapper.eq(PayPlan::getOutTradeNo,outTradeNo);
        PayPlan payPlan = iPayPlanService.getOne(payPlanLambdaQueryWrapper);
        AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payPlan.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("=====退款成功====");
            payPlan.setState(4);
            payPlan.setUpdateTime(new Date());
            iPayPlanService.updateById(payPlan);
            return "success";
        } else {
            System.out.println("====退款失败===");
            return "error";
        }
    }

    @RequestMapping("makeCode")
    public String makeCode(Integer id){
        final SysGoods sysGoods = iSysGoodsService.getById(id);
        SysMakeCode sysMakeCode = new SysMakeCode();
        sysMakeCode.setAddr("http://172.20.10.5:8080/qrcode?cropNumbering="+sysGoods.getCropNumbering());
        sysMakeCode.setCropNumbering(sysGoods.getCropNumbering());
        iSysMakeCodeService.saveOrUpdate(sysMakeCode);
        return "success";
    }

    @RequestMapping("getByMakeCropNumbering")
    public SysMakeCode getByMakeCropNumbering(String cropNumbering){
        LambdaQueryWrapper<SysMakeCode> sysMakeCodeQueryWrapper = new LambdaQueryWrapper<>();
        sysMakeCodeQueryWrapper.eq(SysMakeCode::getCropNumbering,cropNumbering);
        SysMakeCode sysMakeCode = iSysMakeCodeService.getOne(sysMakeCodeQueryWrapper);
        return sysMakeCode;
    }
}
